// websocket_client.cpp
#include "websocket_client.h"
#include "mongoose.h"
#include <thread>
#include <chrono>
#include <stdio.h>

static struct mg_mgr g_mgr;
static struct mg_connection* g_conn = NULL;
static ws_message_callback_t g_ws_cb = NULL;
static bool g_running = false;
static std::string g_url;

// Mongoose 事件处理器
static void fn(struct mg_connection* c, int ev, void* ev_data) {
    if (ev == MG_EV_ERROR) {
        // 连接错误
        fprintf(stderr, "Mongoose error: %s\n", (char *)ev_data);
    } else if (ev == MG_EV_OPEN) {
        // TCP 连接已建立
        printf("TCP connection to %s established.\n", g_url.c_str());
    } else if (ev == MG_EV_WS_OPEN) {
        // WebSocket 握手成功
        printf("WebSocket connection to %s opened.\n", g_url.c_str());
        g_conn = c; // 保存连接
    } else if (ev == MG_EV_WS_MSG) {
        // 收到 WebSocket 消息
        struct mg_ws_message* wm = (struct mg_ws_message*)ev_data;
        printf("Received command from server: %.*s\n", (int)wm->data.len, wm->data.buf);
        if (g_ws_cb) {
            // 通过回调函数处理命令
            g_ws_cb(wm->data.buf, wm->data.len);
        }
    } else if (ev == MG_EV_CLOSE) {
        // 连接关闭
        printf("Connection closed.\n");
        g_conn = NULL; // 清除连接，轮询循环将尝试重连
    }
}

void websocket_client_start(const std::string& url, ws_message_callback_t cb) {
    g_url = url;
    g_ws_cb = cb;
    g_running = true;

    mg_mgr_init(&g_mgr);
    printf("WebSocket client starting...\n");

    while (g_running) {
        // 如果未连接，则尝试连接
        if (g_conn == NULL) {
            printf("Attempting to connect to %s...\n", g_url.c_str());
            // 使用 mg_ws_connect 进行客户端连接
            mg_ws_connect(&g_mgr, g_url.c_str(), fn, NULL, NULL);
        }
        mg_mgr_poll(&g_mgr, 1000); // 轮询事件，超时1秒
    }

    mg_mgr_free(&g_mgr);
    printf("WebSocket client stopped.\n");
}

void websocket_client_stop() {
    if (g_running) {
        g_running = false;
    }
}

bool websocket_client_send(const char* message, size_t len) {
    if (g_conn != NULL) {
        mg_ws_send(g_conn, message, len, WEBSOCKET_OP_TEXT);
        return true;
    }
    // 如果未连接，则无法发送
    fprintf(stderr, "Cannot send message, not connected.\n");
    return false;
}